#!/bin/bash

# 工程实践平台Linux环境安装脚本
# 支持 Ubuntu/Debian/CentOS/RHEL 系统
# 使用方法: bash install-linux.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        log_error "请不要使用root用户运行此脚本，请使用普通用户运行"
        exit 1
    fi
}

# 检测操作系统
detect_os() {
    log_info "检测操作系统..."
    
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
        ID=$ID
    else
        log_error "无法检测系统版本"
        exit 1
    fi
    
    log_info "检测到系统: $OS $VER ($ID)"
    
    # 检查是否为支持的版本
    if [[ "$ID" == "ubuntu" && "$VER" < "20.04" ]]; then
        log_warning "Ubuntu版本过低，建议使用20.04或更高版本"
    elif [[ "$ID" == "debian" && "$VER" < "11" ]]; then
        log_warning "Debian版本过低，建议使用11或更高版本"
    elif [[ "$ID" == "centos" && "$VER" < "8" ]]; then
        log_warning "CentOS版本过低，建议使用8或更高版本"
    fi
}

# 安装函数
install_package() {
    local package=$1
    local install_cmd=$2
    local check_cmd=$3
    
    if [[ -n "$check_cmd" ]]; then
        if eval $check_cmd &> /dev/null; then
            log_info "$package 已安装"
            return 0
        fi
    elif command -v $package &> /dev/null; then
        log_info "$package 已安装"
        return 0
    fi
    
    log_info "正在安装 $package..."
    if eval $install_cmd; then
        log_success "$package 安装完成"
    else
        log_error "$package 安装失败"
        return 1
    fi
}

# Ubuntu/Debian安装
install_ubuntu_debian() {
    log_info "检测到Ubuntu/Debian系统，使用apt包管理器"
    
    # 更新系统
    log_info "更新系统包列表..."
    sudo apt update
    
    # 安装基础工具
    log_info "安装基础工具..."
    sudo apt install -y curl wget git unzip software-properties-common \
                       apt-transport-https ca-certificates gnupg lsb-release
    
    # 安装Java 17
    install_package "java" "sudo apt install -y openjdk-17-jdk openjdk-17-jre" \
                   "java -version 2>&1 | head -n 1 | grep -q '17'"
    
    # 安装Maven
    install_package "mvn" "sudo apt install -y maven" \
                   "mvn -version | head -n 1 | grep -q 'Apache Maven'"
    
    # 安装Docker
    install_package "docker" "sudo apt install -y docker.io docker-compose" \
                   "docker --version"
    
    # 启动Docker服务
    sudo systemctl start docker
    sudo systemctl enable docker
    sudo usermod -aG docker $USER
    
    # 安装kubectl（可选）
    if [[ "$1" == "with-k8s" ]]; then
        log_info "安装kubectl..."
        curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
        sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
        rm kubectl
        log_success "kubectl安装完成"
    fi
}

# CentOS/RHEL安装
install_centos_rhel() {
    log_info "检测到CentOS/RHEL系统，使用yum包管理器"
    
    # 更新系统
    log_info "更新系统包列表..."
    sudo yum update -y
    
    # 安装基础工具
    log_info "安装基础工具..."
    sudo yum install -y curl wget git unzip
    
    # 安装Java 17
    install_package "java" "sudo yum install -y java-17-openjdk-devel" \
                   "java -version 2>&1 | head -n 1 | grep -q '17'"
    
    # 安装Maven
    install_package "mvn" "sudo yum install -y maven" \
                   "mvn -version | head -n 1 | grep -q 'Apache Maven'"
    
    # 安装Docker
    install_package "docker" "sudo yum install -y docker docker-compose" \
                   "docker --version"
    
    # 启动Docker服务
    sudo systemctl start docker
    sudo systemctl enable docker
    sudo usermod -aG docker $USER
}

# 配置Docker镜像加速器
configure_docker_mirrors() {
    log_info "配置Docker镜像加速器..."
    
    sudo mkdir -p /etc/docker
    
    cat > /tmp/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com",
    "https://registry.docker-cn.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}
EOF
    
    sudo mv /tmp/daemon.json /etc/docker/daemon.json
    
    # 重启Docker服务
    sudo systemctl restart docker
    
    log_success "Docker镜像加速器配置完成"
}

# 验证安装
verify_installation() {
    log_info "验证安装结果..."
    
    echo
    echo "=========================================="
    echo "安装验证结果"
    echo "=========================================="
    
    # 检查Java
    if command -v java &> /dev/null; then
        JAVA_VERSION=$(java -version 2>&1 | head -n 1)
        echo "✅ Java: $JAVA_VERSION"
    else
        echo "❌ Java: 未安装"
    fi
    
    # 检查Maven
    if command -v mvn &> /dev/null; then
        MAVEN_VERSION=$(mvn -version | head -n 1)
        echo "✅ Maven: $MAVEN_VERSION"
    else
        echo "❌ Maven: 未安装"
    fi
    
    # 检查Docker
    if command -v docker &> /dev/null; then
        DOCKER_VERSION=$(docker --version)
        echo "✅ Docker: $DOCKER_VERSION"
    else
        echo "❌ Docker: 未安装"
    fi
    
    # 检查Docker Compose
    if command -v docker-compose &> /dev/null; then
        COMPOSE_VERSION=$(docker-compose --version)
        echo "✅ Docker Compose: $COMPOSE_VERSION"
    else
        echo "❌ Docker Compose: 未安装"
    fi
    
    # 检查kubectl（如果安装了）
    if command -v kubectl &> /dev/null; then
        KUBECTL_VERSION=$(kubectl version --client --short)
        echo "✅ kubectl: $KUBECTL_VERSION"
    fi
    
    echo "=========================================="
}

# 显示后续步骤
show_next_steps() {
    log_success "=========================================="
    log_success "环境安装完成！"
    log_success "=========================================="
    echo
    echo "下一步操作："
    echo "1. 重新登录或执行: newgrp docker"
    echo "2. 验证Docker权限: docker ps"
    echo "3. 构建项目: mvn clean package -DskipTests"
    echo "4. 启动平台: ./scripts/start.sh"
    echo
    echo "Docker镜像加速器已配置，下载速度会更快"
    echo "如有问题，请查看错误信息或联系技术支持"
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台Linux环境安装脚本"
    echo "=========================================="
    echo
    
    # 检查系统要求
    check_root
    detect_os
    
    # 根据系统类型安装
    if [[ "$ID" == "ubuntu" || "$ID" == "debian" ]]; then
        install_ubuntu_debian "$1"
    elif [[ "$ID" == "centos" || "$ID" == "rhel" || "$ID" == "rocky" || "$ID" == "alma" ]]; then
        install_centos_rhel
    else
        log_error "不支持的操作系统: $OS"
        exit 1
    fi
    
    # 配置Docker镜像加速器
    configure_docker_mirrors
    
    # 验证安装
    verify_installation
    
    # 显示后续步骤
    show_next_steps
}

# 显示帮助信息
show_help() {
    echo "使用方法: $0 [选项]"
    echo
    echo "选项:"
    echo "  with-k8s    同时安装Kubernetes工具(kubectl)"
    echo "  help        显示此帮助信息"
    echo
    echo "示例:"
    echo "  $0              # 安装基础环境"
    echo "  $0 with-k8s     # 安装基础环境 + Kubernetes工具"
}

# 处理命令行参数
case "${1:-}" in
    "help"|"-h"|"--help")
        show_help
        exit 0
        ;;
    "with-k8s")
        main "with-k8s"
        ;;
    "")
        main
        ;;
    *)
        log_error "未知选项: $1"
        show_help
        exit 1
        ;;
esac 